package com.shiwaixiangcun.customer.module.intelligent

import android.os.Bundle
import android.view.View
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_add_share.*
import kotlinx.android.synthetic.main.top_bar_white.*

/**
 * 添加分享用户
 */
class AddShareActivity : BaseActivity() {
    private var strToken: String? = null
    private var deviceId: String = ""
    private var channelId = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_share)
        initBundleData()
        initView()
    }

    private fun initBundleData() {

        deviceId = intent.extras.getString("deviceId", "")
        channelId = intent.extras.getInt("channelId", 0)
    }

    private fun initView() {
        back_left.setOnClickListener { finish() }
        tv_page_name.text = "添加分享设备"
        tv_top_right.text = "确定"
        tv_top_right.visibility = View.VISIBLE

        tv_top_right.setOnClickListener {
            if (edt_share_account.text.toString().isNotEmpty()) {
                addShareDevice()
            } else {
                showToastShort("请输入对方的世外生活账号")
            }
        }
    }

    private fun addShareDevice() {

        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String


        OkGo.post<String>(GlobalApi.addShare)
                .params("access_token", strToken)
                .params("deviceId", deviceId)
                .params("channelId", channelId)
                .params("shareAccount", edt_share_account.text.toString())
                .execute(object : StringDialogCallBack(this) {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<Any>>() {}.type
                        val backData = JsonUtil.fromJson<DeviceBaseEntity<Any>>(response?.body(), type)
                        when (backData.responseCode) {
                            1001 -> {
                                showToastShort("添加分享成功")
                                finish()
                            }
                            else -> showToastShort(backData.message)
                        }
                    }

                })
    }
}
